import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import styleImport from 'vite-plugin-style-import'
import viteTsconfigPaths from 'vite-tsconfig-paths'

// https://vitejs.dev/config/
export default ({ mode }) => {
  Object.assign(process.env, loadEnv(mode, process.cwd()))

  const port = Number(process.env.VITE_APP_PORT)
  const proxyPrefix = process.env.VITE_APP_DEVELOPMENT_PROXY_PREFIX
  const productionUrl = process.env.VITE_APP_PRODUCTION_URL

  return defineConfig({
    plugins: [
      vue(),
      styleImport({
        libs: [
          {
            libraryName: 'vant',
            esModule: true,
            resolveStyle: (name) => `vant/es/${name}/style`
          }
        ]
      }),
      viteTsconfigPaths({
        root: './',
        extensions: ['.js', '.ts', '.jsx', '.tsx', '.vue']
      })
    ],
    base: './', // 设置打包路径
    server: {
      port, // 设置服务启动端口号
      open: true, // 设置服务启动时是否自动打开浏览器
      cors: true, // 允许跨域

      // 设置代理，根据我们项目实际情况配置
      proxy: {
        [proxyPrefix]: {
          target: productionUrl,
          changeOrigin: true,
          secure: false,
          rewrite: (path) => path.replace(proxyPrefix, '')
        }
      }
    }
  })
}
